const fs = require("fs");
const router = require("koa-router")();

// 配置控制器
function setController(mapping, filename) {
  let path = mapping["url"];
  let method = mapping["method"].toUpperCase();
  let controller = mapping["controller"];
  if (method == "GET") {
    router.get(path, controller);
  } else if (method == "POST") {
    router.post(path, controller);
  } else if (method == "PUT") {
    router.put(path, controller);
  } else if (method == "DELETE") {
    router.delete(path, controller);
  } else if (method == "PATCH") {
    router.patch(path, controller);
  } else {
    console.log(`invalid URL: ${path}`);
  }
}

// 路由映射
function routerMap(mappings, filename) {
  console.log("mappings", mappings);
  let keys = Object.keys(mappings);
  if (keys.includes("controller") && keys.includes("method")) {
    setController(mappings, filename);
  } else {
    keys.forEach(key => {
      setController(mappings[key], filename);
    });
  }
}

// 添加控制器
function addControllers(path) {
  let basePath = __dirname + "/" + path;
  let dirs = fs.readdirSync(basePath);
  for (let dir of dirs) {
    let dirPath = basePath + "/" + dir;
    files = fs.readdirSync(dirPath);
    //取出所有的js文件
    let js_files = files.filter(f => {
      return f.endsWith(".js");
    });
    for (let f of js_files) {
      let filename = "/".concat(f.replace(".js", "").trim());
      let mapping = require(dirPath + "/" + f);
      routerMap(mapping, filename);
    }
  }
}

module.exports = function(dir) {
  let startTime = new Date();
  let controller_dir = dir || "controllers";
  addControllers(controller_dir);
  console.log("timeForRouterMap", new Date() - startTime);
  return router;
};
